<template>
  <div class="system-logs">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1>操作日志</h1>
      <p>查看系统中所有管理员的操作记录</p>
    </div>

    <!-- 搜索工具栏 -->
    <div class="toolbar">
      <el-form :model="searchForm" class="search-form" inline>
        <el-form-item label="管理员ID">
          <el-input v-model="searchForm.adminId" placeholder="请输入管理员ID" clearable />
        </el-form-item>
        <el-form-item label="功能模块">
          <el-select v-model="searchForm.module" placeholder="请选择功能模块" clearable>
            <el-option label="全部" value="" />
            <el-option label="用户管理" value="user" />
            <el-option label="积分管理" value="credits" />
            <el-option label="订单管理" value="orders" />
            <el-option label="系统管理" value="system" />
          </el-select>
        </el-form-item>
        <el-form-item label="操作类型">
          <el-input v-model="searchForm.operation" placeholder="请输入操作类型" clearable />
        </el-form-item>
        <el-form-item label="时间范围">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
      
      <div class="toolbar-actions">
        <el-button type="success" @click="handleExport">
          <el-icon><Download /></el-icon>
          导出日志
        </el-button>
        <el-button type="danger" @click="handleClearLogs">
          <el-icon><Delete /></el-icon>
          清理日志
        </el-button>
        <el-button type="primary" @click="handleRefresh">
          <el-icon><Refresh /></el-icon>
          刷新
        </el-button>
      </div>
    </div>

    <!-- 日志列表 -->
    <div class="content-card">
      <el-table
        :data="logsList"
        :loading="loading"
        stripe
        style="width: 100%"
        row-key="id"
      >
        <el-table-column prop="id" label="日志ID" width="80" />
        <el-table-column prop="adminName" label="操作人" width="120">
          <template #default="scope">
            <div class="admin-info">
              <span class="admin-name">{{ scope.row.adminName }}</span>
              <span class="admin-id">ID: {{ scope.row.adminId }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="module" label="功能模块" width="100">
          <template #default="scope">
            <el-tag :type="getModuleTagType(scope.row.module)">
              {{ getModuleText(scope.row.module) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="operation" label="操作类型" width="120" />
        <el-table-column prop="description" label="操作描述" min-width="200" show-overflow-tooltip />
        <el-table-column prop="ipAddress" label="IP地址" width="130" />
        <el-table-column prop="status" label="执行状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
              {{ scope.row.status === 1 ? '成功' : '失败' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="executionTime" label="执行时间" width="100">
          <template #default="scope">
            <span :class="getExecutionTimeClass(scope.row.executionTime)">
              {{ scope.row.executionTime }}ms
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="操作时间" width="170">
          <template #default="scope">
            {{ formatDate(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="scope">
            <el-button type="primary" size="small" @click="showLogDetail(scope.row)">
              <el-icon><View /></el-icon>
              详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :small="false"
          :disabled="loading"
          :background="true"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 日志详情弹窗 -->
    <el-dialog v-model="logDetailVisible" title="操作日志详情" width="800px" :close-on-click-modal="false">
      <div v-if="currentLog" class="log-detail">
        <!-- 基本信息 -->
        <div class="detail-section">
          <h4>基本信息</h4>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="日志ID">{{ currentLog.id }}</el-descriptions-item>
            <el-descriptions-item label="操作人">{{ currentLog.adminName }} (ID: {{ currentLog.adminId }})</el-descriptions-item>
            <el-descriptions-item label="功能模块">
              <el-tag :type="getModuleTagType(currentLog.module)">{{ getModuleText(currentLog.module) }}</el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="操作类型">{{ currentLog.operation }}</el-descriptions-item>
            <el-descriptions-item label="执行状态">
              <el-tag :type="currentLog.status === 1 ? 'success' : 'danger'">
                {{ currentLog.status === 1 ? '成功' : '失败' }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="执行时间">
              <span :class="getExecutionTimeClass(currentLog.executionTime)">
                {{ currentLog.executionTime }}ms
              </span>
            </el-descriptions-item>
            <el-descriptions-item label="IP地址">{{ currentLog.ipAddress }}</el-descriptions-item>
            <el-descriptions-item label="操作时间">{{ formatDate(currentLog.createTime) }}</el-descriptions-item>
          </el-descriptions>
        </div>

        <!-- 详细描述 -->
        <div class="detail-section">
          <h4>操作描述</h4>
          <div class="description-content">
            {{ currentLog.description || '无详细描述' }}
          </div>
        </div>

        <!-- 请求信息 -->
        <div class="detail-section" v-if="currentLog.requestUrl">
          <h4>请求信息</h4>
          <el-descriptions :column="1" border>
            <el-descriptions-item label="请求URL">{{ currentLog.requestUrl }}</el-descriptions-item>
            <el-descriptions-item label="请求方法">
              <el-tag :type="getMethodTagType(currentLog.requestMethod)">
                {{ currentLog.requestMethod }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="用户代理" v-if="currentLog.userAgent">
              <div class="user-agent">{{ currentLog.userAgent }}</div>
            </el-descriptions-item>
          </el-descriptions>
        </div>

        <!-- 请求参数 -->
        <div class="detail-section" v-if="currentLog.requestParams">
          <h4>请求参数</h4>
          <pre class="json-content">{{ formatJSON(currentLog.requestParams) }}</pre>
        </div>

        <!-- 响应结果 -->
        <div class="detail-section" v-if="currentLog.responseResult">
          <h4>响应结果</h4>
          <pre class="json-content">{{ formatJSON(currentLog.responseResult) }}</pre>
        </div>
      </div>
      
      <template #footer>
        <el-button @click="logDetailVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getOperationLogs } from '@/api'

// 响应式数据
const loading = ref(false)
const logsList = ref<any[]>([])
const logDetailVisible = ref(false)
const currentLog = ref<any>(null)

// 搜索表单
const searchForm = reactive({
  adminId: '',
  module: '',
  operation: '',
  dateRange: null as any
})

// 分页数据
const pagination = reactive({
  page: 1,
  size: 20,
  total: 0
})

// 加载日志列表
const loadLogsList = async () => {
  try {
    loading.value = true
    
    const params = {
      current: pagination.page,
      size: pagination.size,
      adminId: searchForm.adminId || undefined,
      module: searchForm.module || undefined,
      operation: searchForm.operation || undefined,
      startTime: searchForm.dateRange?.[0],
      endTime: searchForm.dateRange?.[1]
    }
    
    const response = await getOperationLogs(params)
    
    if (response && response.success) {
      logsList.value = response.data?.data || []
      pagination.total = response.data?.total || 0
    } else {
      logsList.value = []
      pagination.total = 0
    }
  } catch (error) {
    console.error('Load logs failed:', error)
    logsList.value = []
    pagination.total = 0
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.page = 1
  loadLogsList()
}

// 重置
const handleReset = () => {
  Object.assign(searchForm, {
    adminId: '',
    module: '',
    operation: '',
    dateRange: null
  })
  pagination.page = 1
  loadLogsList()
}

// 刷新
const handleRefresh = () => {
  loadLogsList()
}

// 显示日志详情
const showLogDetail = (log: any) => {
  currentLog.value = log
  logDetailVisible.value = true
}

// 导出日志
const handleExport = async () => {
  try {
    // 获取全部数据
    const params = {
      current: 1,
      size: 999999,
      adminId: searchForm.adminId || undefined,
      module: searchForm.module || undefined,
      operation: searchForm.operation || undefined,
      startTime: searchForm.dateRange?.[0],
      endTime: searchForm.dateRange?.[1]
    }
    
    const response = await getOperationLogs(params)
    const data = response.data?.data || []
    
    if (data.length === 0) {
      ElMessage.warning('没有数据可导出')
      return
    }
    
    exportLogsToCSV(data)
    ElMessage.success(`成功导出 ${data.length} 条日志`)
  } catch (error) {
    ElMessage.error('导出失败')
  }
}

// 导出CSV
const exportLogsToCSV = (data: any[]) => {
  const headers = ['日志ID', '操作人', '功能模块', '操作类型', '操作描述', 'IP地址', '执行状态', '执行时间(ms)', '操作时间']
  const csvContent = [
    headers.join(','),
    ...data.map(log => [
      log.id,
      `${log.adminName}(${log.adminId})`,
      getModuleText(log.module),
      log.operation,
      log.description || '',
      log.ipAddress || '',
      log.status === 1 ? '成功' : '失败',
      log.executionTime || 0,
      formatDate(log.createTime)
    ].join(','))
  ].join('\n')
  
  const blob = new Blob(['\uFEFF' + csvContent], { type: 'text/csv;charset=utf-8;' })
  const link = document.createElement('a')
  link.href = URL.createObjectURL(blob)
  link.download = `操作日志_${new Date().getTime()}.csv`
  link.click()
}

// 清理日志
const handleClearLogs = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要清理历史日志吗？此操作不可恢复！',
      '确认清理',
      { type: 'warning' }
    )
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    ElMessage.success('历史日志清理完成')
    loadLogsList()
  } catch (error) {
    // 用户取消操作
  }
}

// 每页数量改变
const handleSizeChange = (size: number) => {
  pagination.size = size
  pagination.page = 1
  loadLogsList()
}

// 当前页改变
const handleCurrentChange = (page: number) => {
  pagination.page = page
  loadLogsList()
}

// 获取模块标签类型
const getModuleTagType = (module: string) => {
  const typeMap: Record<string, string> = {
    user: 'primary',
    credits: 'warning',
    orders: 'success',
    system: 'danger'
  }
  return typeMap[module] || 'info'
}

// 获取模块文本
const getModuleText = (module: string) => {
  const textMap: Record<string, string> = {
    user: '用户管理',
    credits: '积分管理',
    orders: '订单管理',
    system: '系统管理'
  }
  return textMap[module] || module
}

// 获取请求方法标签类型
const getMethodTagType = (method: string) => {
  const typeMap: Record<string, string> = {
    GET: 'info',
    POST: 'success',
    PUT: 'warning',
    DELETE: 'danger'
  }
  return typeMap[method] || 'info'
}

// 获取执行时间样式类
const getExecutionTimeClass = (time: number) => {
  if (time > 1000) return 'execution-slow'
  if (time > 500) return 'execution-medium'
  return 'execution-fast'
}

// 格式化JSON
const formatJSON = (jsonStr: string) => {
  try {
    const obj = JSON.parse(jsonStr)
    return JSON.stringify(obj, null, 2)
  } catch {
    return jsonStr
  }
}

// 格式化日期
const formatDate = (date: Date | string) => {
  if (!date) return '-'
  const d = new Date(date)
  return d.toLocaleString('zh-CN')
}

// 页面加载
onMounted(() => {
  loadLogsList()
})
</script>

<style scoped>
.system-logs {
  padding: 0;
}

.pagination {
  margin-top: 20px;
  justify-content: center;
}

.admin-info {
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.admin-name {
  font-weight: 600;
  color: #303133;
}

.admin-id {
  font-size: 12px;
  color: #909399;
}

.execution-fast {
  color: #67c23a;
}

.execution-medium {
  color: #e6a23c;
}

.execution-slow {
  color: #f56c6c;
}

.log-detail {
  max-height: 70vh;
  overflow-y: auto;
}

.detail-section {
  margin-bottom: 24px;
}

.detail-section h4 {
  margin: 0 0 12px 0;
  color: #303133;
  font-size: 16px;
  font-weight: 600;
}

.description-content {
  padding: 12px;
  background: #f5f7fa;
  border-radius: 4px;
  color: #606266;
  line-height: 1.6;
}

.json-content {
  background: #f8f9fa;
  border: 1px solid #e9ecef;
  border-radius: 4px;
  padding: 16px;
  font-family: 'Courier New', monospace;
  font-size: 12px;
  line-height: 1.4;
  overflow-x: auto;
  max-height: 300px;
  overflow-y: auto;
}

.user-agent {
  font-size: 12px;
  color: #606266;
  word-break: break-all;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .toolbar {
    flex-direction: column;
    gap: 16px;
  }
  
  .search-form {
    width: 100%;
  }
  
  .toolbar-actions {
    justify-content: flex-start;
  }
  
  .log-detail {
    max-height: 60vh;
  }
}
</style>
